<template>
    <el-card class="pending-requests-container">
        <div v-if="pendingRequests.length!=0">
            <h2>待接受好友列表</h2>
            <el-table  :data="pendingRequests" style="width: 100%" v-loading="loading">
                <el-table-column prop="username" label="用户名"></el-table-column>
                <el-table-column prop="createdAt" label="请求时间"></el-table-column>
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <el-button type="success" @click="acceptRequest(row)" icon="el-icon-check">接收好友</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-empty class="empty" v-else description="暂无好友请求信息" />
    </el-card>
</template>


<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { acceptFriendRequest, getPendingFriendRequests } from '@/service/user/friendShipService';
export default defineComponent({
    setup() {
        const userId = ref<number>(parseInt(localStorage.getItem("userId") || "0"));
        const pendingRequests = ref<any[]>([]);
        const loading = ref(false);
        // 获取待接受好友列表
        const fetchPendingRequests = async () => {
            loading.value = true;
            try {
                const response = await getPendingFriendRequests(userId.value);
                if (response.status === 200 && response.success) {
                    pendingRequests.value = response.data;
                } else {
                    throw new Error('Failed to fetch pending requests due to server response');
                }
            } catch (error: any) {
                ElMessage.error(error.message || 'Failed to retrieve pending friend requests.');
            } finally {
                loading.value = false;
            }
        };
        //   接收好友
        const acceptRequest = async (user: any) => {
            try {
                const response = await acceptFriendRequest(userId.value, user.userId);
                ElMessage.success(response.message || 'Friend request accepted.');
                fetchPendingRequests();
            } catch (error: any) {
                ElMessage.error(error.message || 'Failed to accept friend request.');
            }
        };

        onMounted(fetchPendingRequests);

        return {
            userId,
            pendingRequests,
            loading,
            fetchPendingRequests,
            acceptRequest
        };
    }
});
</script>

<style lang="less" scoped>
.pending-requests-container {
    width: 100%;
    min-height: 85vh;
    .empty{
        width:100%;
        min-height:70vh;
    }
}
</style>